import { cloneDeep } from "lodash-es";
import { globalConfig, resourceApiAliasConfig } from "../index";
/**
 * 主要用于资源数组的树结构拼接
 */
export function invertTree({
    sourceArr,
    lazy = false,
    callback = (node) => {},
    grantedCodes = [],
  }) {
    const {
      idKeyAlias,
      pidKeyAlias,
      childrenKeyAlias,
      hasChildrenAlias,
      ordinalKeyAlias,
    } = resourceApiAliasConfig;
    const obj = {};
    const allNotCompleteLazyObj = {};
    //如果有排序字段先排序
    if (sourceArr.length > 0 && sourceArr[0].hasOwnProperty(ordinalKeyAlias)) {
      sourceArr.sort((a, b) => {
        return a[ordinalKeyAlias] <= b[ordinalKeyAlias];
      });
    } else if (sourceArr.length > 0) {
      sourceArr.sort((a, b) => {
        if (a[pidKeyAlias] === null && b[pidKeyAlias] !== null) {
          return -1;
        } else {
          return 1;
        }
      });
    }
  
    for (let i = 0; i < sourceArr.length; i++) {
      sourceArr[i][childrenKeyAlias] = [];
      sourceArr[i][hasChildrenAlias] = false;
      sourceArr[i]["isLeaf"] = true;
  
      obj[sourceArr[i][idKeyAlias]] = sourceArr[i];
      allNotCompleteLazyObj[sourceArr[i][idKeyAlias]] = cloneDeep(sourceArr[i]);
    }
    const result = []; //完整的树
    const options = [];
    const allNotCompleteLazyResult = []; // 懒加载的不完整的树
    sourceArr.forEach((node, nodeIdx) => {
      // FIXME:循环的时候需要获取 权限code
      callback(node, grantedCodes, sourceArr);
      // FIXME:////////////////
      //一级节点满足的条件
      if (!obj[node[pidKeyAlias]]) {
        result.push(node);
        allNotCompleteLazyResult.push(
          allNotCompleteLazyObj[sourceArr[nodeIdx][idKeyAlias]]
        );
        return;
      }
      //因为obj与sourceArr里的元素 都引用自同一个node
      obj[node[pidKeyAlias]][childrenKeyAlias] =
        obj[node[pidKeyAlias]][childrenKeyAlias] || [];
      obj[node[pidKeyAlias]][childrenKeyAlias].push(node);
      //obj[node[pidKeyAlias]][childrenKeyAlias].length===0 ? obj[node[pidKeyAlias]][hasChildrenAlias] = false : obj[node[pidKeyAlias]][hasChildrenAlias] = true;
  
      if (lazy) {
        obj[node[pidKeyAlias]][hasChildrenAlias] = true;
        allNotCompleteLazyObj[node[pidKeyAlias]][hasChildrenAlias] = true;
        obj[node[pidKeyAlias]]["isLeaf"] = false;
        allNotCompleteLazyObj[node[pidKeyAlias]]["isLeaf"] = false;
        //console.log(node,'当前节点',allNotCompleteLazyObj[node[pidKeyAlias]])
      } else {
        allNotCompleteLazyObj[node[pidKeyAlias]][childrenKeyAlias] =
          allNotCompleteLazyObj[node[pidKeyAlias]][childrenKeyAlias] || [];
        allNotCompleteLazyObj[node[pidKeyAlias]][childrenKeyAlias].push(
          allNotCompleteLazyObj[sourceArr[nodeIdx][idKeyAlias]]
        );
      }
    });
    return { allNotCompleteLazyResult, result };
  }
  
  /* renameKey(treeData, oldKey, newKey) {
    if (!Array.isArray(treeData)) {
      return null;
    }
    return treeData.map(node => {
      const newNode = { ...node };
      if (oldKey in node) {
        newNode[newKey] = newNode[oldKey];
        delete newNode[oldKey];
      }
      if (newNode.children) {
        newNode.children = renameKey(newNode.children, oldKey, newKey);
      }
      return newNode;
    });
  } */
  export const renameTreeKeys = ({ treeData, renameKeyMapping = [] }) => {
    if (!Array.isArray(treeData)) {
      if (
        treeData.hasOwnProperty("children") &&
        Array.isArray(treeData["children"])
      ) {
        const newTreeData = JSON.parse(JSON.stringify(treeData));
        renameKeyMapping.forEach((o) => {
          if (o.oldKey in node) {
            newTreeData[o.newKey] = newTreeData[o.oldKey];
            delete newTreeData[o.oldKey];
          }
        });
        return renameTreeKeys({
          treeData: newTreeData.children,
          renameKeyMapping,
        });
      } else {
        return null;
      }
    }
    const newTreeData = JSON.parse(JSON.stringify(treeData));
    return newTreeData.map((node) => {
      const newNode = { ...node };
      renameKeyMapping.forEach((o) => {
        if (o.oldKey in node) {
          newNode[o.newKey] = newNode[o.oldKey];
          delete newNode[o.oldKey];
        }
      });
      if (newNode.children) {
        newNode.children = renameTreeKeys({
          treeData: newNode.children,
          renameKeyMapping,
        });
      }
      return newNode;
    });
  };
  const filterTree = ({treeData, filterFunc})=> {
    if (!Array.isArray(treeData)) {
      return [];
    }
    const filteredNodes = [];
    treeData.forEach(node => {
      if (filterFunc(node)) {
        filteredNodes.push(node);
      }
      if (node.children) {
        filteredNodes.push(...filterTree({treeData:node.children, filterFunc}));
      }
    });
    return filteredNodes;
  }

  export default {
    renameTreeKeys,
    invertTree,
    filterTree
  };